import bpy
import os

source_folder = 'C:/Users/zhangXX/Music/jntm'
output_folder = 'C:/Users/zhangXX/Music/jntm2'

bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()

for file_name in os.listdir(source_folder):
    if file_name.endswith('.stl') or file_name.endswith('.STL'):
        bpy.ops.object.select_all(action='SELECT')
        bpy.ops.object.delete()
        file_path = os.path.join(source_folder, file_name)
        
        bpy.ops.import_mesh.stl(filepath=file_path, global_scale=1, use_scene_unit=True, axis_forward='Y', axis_up='Z')
        
        bpy.ops.object.select_all(action='SELECT')
        obj = bpy.context.selected_objects[0]

        mat = bpy.data.materials.new(name="MetalGreen")
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        bsdf = nodes["原理化BSDF"]
        if not bsdf:
            bsdf = nodes.new(type='ShaderNodeBsdfPrincipled')
        bsdf.inputs[0].default_value = (0.0, 1.0, 0.0, 1)
        bsdf.inputs[1].default_value = 1.0
        bsdf.inputs[2].default_value = 0.5
        
        if obj.data.materials:
            obj.data.materials[0] = mat
        else:
            obj.data.materials.append(mat)

        output_file_name = os.path.splitext(file_name)[0] + '.dae'
        output_path = os.path.join(output_folder, output_file_name)
        bpy.ops.wm.collada_export(filepath=output_path,selected=True, include_children=True,export_global_forward_selection='Z',export_global_up_selection='-Y')


bpy.ops.object.select_all(action='SELECT')
bpy.ops.object.delete()
        
